﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace Meteo.Desktop
{
    public class MeteoService
    {
        private static HashSet<MeteoInterface> listeners = new HashSet<MeteoInterface>();
        private static object lockthis = new object();
        private static int updateTime = 1;

        public static int UpdateTime
        {
            get
            {
                return updateTime;
            }
            set
            {
                updateTime = value;
            }
        }

        public static bool add(MeteoInterface litener){
            bool ret;
            lock (lockthis)
                ret = listeners.Add(litener);

            return ret;
        }

        public static bool remove(MeteoInterface litener)
        {
            bool ret;
            lock (lockthis)
                ret = listeners.Add(litener);

            return ret;
        }

        public static void service()
        {
            try
            {
                // Do service stuff here
                while (true)
                {
                    // Crear el objeto Meteo
                    Meteo met = new Meteo();

                    // Notificar a los listeners que hay información disponible
                    lock (lockthis)
                    {
                        foreach (MeteoInterface listener in listeners)
                            listener.notify(met.getData());
                    }

                    // Al finalizar, dormirse un rato
                    // La información meteorológica se actualizará cada 10 minutos
                    Thread.Sleep(new TimeSpan(0, 0, updateTime, 0));
                }
            }
            catch (ThreadAbortException) { }
        }
    }
}
